package com.axonactive.yolo.monitor;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.axonactive.yolo.domain.SubscribedFlight;
import com.axonactive.yolo.exception.SubcribedFlightNotFoundException;
import com.axonactive.yolo.service.interfaces.SubscribedFlightService;
import com.axonactive.yolo.util.CONSTANTS;
import com.axonactive.yolo.util.ConvertUnixTime;

public class CheckAvailableFlightJob {
	private final static Logger LOGGER = Logger
			.getLogger(CheckAvailableFlightJob.class);
	@Autowired
	private SubscribedFlightService subcribedFlightService;
	private static int counter=0;

	/**
	 * detect the flights are unavailable
	 * 
	 * @return true if it detects successfully, otherwise return false
	 * @throws SubcribedFlightNotFoundException
	 */
	public boolean run() {
		LOGGER.info("re run check available flight job "+ ++counter);
		try {
			// get list of available flights
			List<SubscribedFlight> subs = getFlights();
			// check if they still available and mark it to unavailable
			getAvailableFlights(subs);
			LOGGER.info("detected "+subs.size()+" flight(s) are unavailable");
		} catch (SubcribedFlightNotFoundException ex) {
			LOGGER.error("detect avaiable flights problems", ex);
			return false;
		}
		return true;
	}

	private List<SubscribedFlight> getAvailableFlights(
			List<SubscribedFlight> subs)
			throws SubcribedFlightNotFoundException {
		int size = subs.size();
		SubscribedFlight sub;
		for (int i = 0; i < size; i++) {
			sub = subs.get(i);
			if (ConvertUnixTime.isFlightUnvailable(sub) == true) {
				sub.setAvailable(CONSTANTS.FLIGHT_UNAVAILABLE);
				subcribedFlightService.updateSubscribedFlight(sub);
				continue;
			}
			subs.remove(i);
			i--;
			size--;
		}
		return subs;
	}

	private List<SubscribedFlight> getFlights() {
		return subcribedFlightService.findAvailableFlights();
	}

}
